package com.djakapm.markdown.editor.action;

import com.djakapm.markdown.editor.AppConstant;
import com.djakapm.markdown.editor.util.ExceptionConsumer;
import com.djakapm.swing.common.ScreenUtil;
import com.djakapm.swing.component.EditorPaneView;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

public class MarkdownSyntaxHelpAction extends AbstractAction {
    private String markdownSyntax;
    private EditorPaneView epv;
    private JDialog dialog;

    public MarkdownSyntaxHelpAction(){
        this.epv = new EditorPaneView();
        this.epv.getComponent().setEditorKitForContentType(AppConstant.HTML_CONTENT_TYPE, new HTMLEditorKit());
        this.epv.getComponent().setContentType(AppConstant.HTML_CONTENT_TYPE);
        this.epv.getComponent().setEditable(false);
        this.dialog = new JDialog();
        this.dialog.getContentPane().add(epv);
        this.dialog.setSize(800,600);
        this.dialog.setModal(true);
        this.dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        this.dialog.setTitle(AppConstant.MARKDOWN_SYNTAX_LABEL);
        this.putValue(Action.NAME,AppConstant.MARKDOWN_SYNTAX_LABEL);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            if(this.markdownSyntax == null){
                this.markdownSyntax = FileUtils.readFileToString(new File(AppConstant.MARKDOWN_SYNTAX_HELP));
            }
            
            this.epv.setText(this.markdownSyntax);
            ScreenUtil.center(this.dialog);
            this.dialog.setVisible(true);
        } catch (IOException e1) {
            ExceptionConsumer.consume(e1);
        }
    }
}
